package com.zadetk.helpyou.net;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by zack on 2018/5/17.
 */

public class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        byte[] valueBytes = value.bytes();
        InputStreamReader charReader = new InputStreamReader(new ByteArrayInputStream(valueBytes), "UTF-8");
        try {
            JsonReader jsonReader = new JsonReader(charReader);
            return adapter.read(jsonReader);
        } catch (JsonSyntaxException e) {
            String json = new String(valueBytes);
            BaseResponse baseResponse = new BaseResponse();
            JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
            JsonPrimitive jsonPrimitive = jsonObject.getAsJsonPrimitive("error_code");
            if (jsonPrimitive != null) {
                baseResponse.setCode(jsonPrimitive.getAsInt());
            }
            JsonElement jsonElement = jsonObject.get("message");
            if (jsonElement != null) {
                baseResponse.setMessage(jsonElement.getAsString());
            }
            return (T) baseResponse;
        } finally {
            value.close();
        }

    }
}
